// 1.定义全局变量

var ctiAddr="172.16.2.166:6013";

var se, m = 0,h = 0,s = 0;

var call1 = null;
var call2 = null;
var currentCallId ="";

var conferenceTag = false;
var lastStateId = "state0";
var isMonitor = false;
var lastAgentState;
var info;

var op_type;

// 技能组和排队数的对应关系
var queueMap = {};

var socket;
var workMode = "ManualIn";
// 初始加载
$(function(){
	// WS初始化
    init();
    // 初始化事件按钮
    //initBtnHandler();
    // 心跳
    _heatData();
    setInterval("_heatData()",50000);
})

//登陆
function loginCTI(usrname,devId) {
    writeLog("loginCTI "+usrname+" "+devId + phone.domain);
    phone.deviceId = devId;
    deviceId = devId;
    _agentLogin(phone.domain,phone.deviceId,usrname,phone.agtPwd,0,"Login","101",workMode);
}


//重置全局变量
function resetGlobalVars() {
	call1 = null;
	call2 = null;
	currentCallId ="";
	conferenceTag = false;
	lastStateId = "state0";
	isMonitor = false;
	lastAgentState;
	info;
	op_type;
}

//连接websocket后端服务器
function init(){
    if(window.WebSocket) {
        //ctiAddr = phone.webUrl.split("://")[1];
        //socket = new WebSocket('ws://'+ctiAddr);
        socket = new WebSocket('ws://'+phone.webUrl);
        // 监听新用户登录
        socket.onmessage = function(event) {
            // JSON.stringify(event)
            //过滤排队数
            //if(JSON.stringify(event.data).indexOf("QueueCallChangeEvt")==-1){
                onMessage("recevice event " + event.data);
            //}
            var evt = JSON.parse(event.data);
            if(evt.code != null){
                if(evt.type == 1){
                     if(evt.code == 200){
                        // 登录成功
                        /*$("#domainS").text(domains);
                        $("#stationnum").text(stationIds);
                        $("#agentnum").text(agentIds);*/
                         e_OnAgentNotReady(0);
                         stateChange(1);
                         window.parent.closeUserDia();
                         writeLog("登录成功");
                         phone.workTime = $.date.dateFormat(new Date(),"HH:mm:ss");
                         //_setAgentState(deviceId, domain, username, pwd, code, "NotReady", "101", workMode);
                         try{
                             setAgtCountInfo(phone.deviceId,phone.workTime,null,$.date.dateFormat(phone.talkTime,'hh:mm:ss'),phone.callCnt+"/"+phone.dialOutCnt,$.date.dateFormat(phone.totalTalkTime,'hh:mm:ss'),phone.agentName,"");
                         }catch(e){}
                     }else if(evt.code == 201){
                         // 设置小休码
                        e_OnAgentNotReady(0);
                        var msg = JSON.parse(evt.errMsg);
                        renderCode(msg);
                     }else if(evt.code == 202){
                         // 设置外显号码
                         onMessage("202 = "+evt.errMsg);
                         var msg = JSON.parse(evt.errMsg);
                         setName(msg.data);
                     }else if(evt.code == 500){
                        writeLog(evt.errMsg);
                        var  err_str = evt.errMsg;
                        if(err_str.indexOf(" get agent not exist fail !")>0){
                            ztoDialog('用户名不存在，'+err_str);
                        }else if(err_str.indexOf(" station not exist !")>0){
                            ztoDialog('分机号不存在，'+err_str);
                        }else if(err_str.indexOf(" agent password error !")>0){
                            ztoDialog('密码错误，请重新输入密码，'+err_str);
                        }else if(err_str.indexOf(" not registered !")>0){
                            ztoDialog('分机未注册，'+err_str);
                        }else if(err_str.indexOf(" already used by ")>0){
                            ztoDialog('分机被使用，'+err_str);
                        } else {
                            ztoDialog('登录失败，请检查坐席号、密码、分机状态是否正常，'+err_str);
                        }
                        return;
                     }
                }else if(evt.type == 2){

                } else if(evt.type == 16){

                }else if(evt.type == 17){
                    e_OnAgentReady();
                    //清空后处理标识
                    phone.isAfterCall = 0;
                }
           }
          
            if(evt.evtName != null){
                setLastCall(evt);
                if(evt.evtName == 'AgentNotReadyEvt'){//未就绪
                    e_OnAgentNotReady(0);
                    //清空后处理标识
                    phone.isAfterCall = 0;
                }else if(evt.evtName == 'AgentReadyEvt'){//就绪
                    e_OnAgentReady();
                    //清空后处理标识
                    phone.isAfterCall = 0;
                }else if(evt.evtName == 'AgentLoggedOnEvt'){//登陆

                }else if(evt.evtName == 'AgentLoggedOffEvt'){//登出
                    e_OnAgentLoggedOff();
                    writeLog("被踢出***");
                }else if(evt.evtName == 'AgentWorkingAfterCallEvt'){
                    e_OnAgentWorkingAfterCall();
                }else if(evt.evtName == 'OriginatedEvt'){//保持通话1
                    e_OnDeliveredEvt(evt);
                }else if(evt.evtName == 'DeliveredEvt'){//振铃
                    e_OnDeliveredEvt(evt);
                }else if(evt.evtName == 'EstablishedEvt'){//接通
                    e_OnEstablishedEvt(evt);
                }else if(evt.evtName == 'ConnectionClearedEvt'){//挂断电话
                    e_OnConnectionClearedEvt(evt);
                }else if(evt.evtName == 'HeldEvt'){//保持通话2
                    e_OnHeldEvt(evt);
                }else if(evt.evtName == 'RetrievedEvt'){//取回通话
                    e_OnRetrievedEvt(evt);
                }else if(evt.evtName == 'ConferencedEvt'){//会议
                    e_OnConferencedEvt(evt);
                }else if(evt.evtName == 'TransferedEvt'){//转移电话
                    e_OnTransferedEvt(evt);
                }else if (evt.evtName == 'QueueCallChangeEvt') {//排队数
                    e_OnQueueNumChangeEvent(evt);
                }
            }
        }
        socket.onopen = function(event) {
            console.log("开启连接");
        }
        socket.onclose = function(event) {
            writeLog("连接关闭");
            socket = new WebSocket('ws://'+phone.webUrl); // 重连
            if(socket.readyState == socket.CLOSED){
                phone.setLogOff();
            }else{
                e_OnAgentLoggedOff();
            }
        }
    }else {
        ztoDialog('浏览器不支持WebSocket!')
    }
}

// 呼叫模型对象
function CallObject() {
    this.callid = '';
    this.ani = '';
    this.dnis = '';
    this.callType = '';
    this.state = '';   // 0 idle[空闲] 1 alerting[告警] 2 connected[连接]  3 hold[保持]
    this.uuid = '';
}


// 设置名字
function setName(data){
    if(data instanceof Array){
         for(var key in data){
            var recode = data[key];
            _setName(recode);
         }
    }
}

function _setName(data){ 
  var html= '<option value='+data.name+'>'+data.name+'</option>';  
  $("#sname").append(html);
}

// 设置小休状态码
function renderCode(data){
    if(data instanceof Array){
        for(var key in data){
			if(key=="erase"){

			}else{
				var record=data[key];
				_renderCode(record);
			}
        }
    }else{
        _renderCode(data);
    }
}

function _renderCode(data) {
	var html = '<li style="width:218px"><a itemdata="' + data.code +
		'" href="#" style="color:#B30000;font-weight:bold; font-size: 12px;">' +'<span style="margin-left: -7px;">'
		+data.codename +'</span>'+'</a></li>';
	$("#auxreasons").append(html);
}

// 设置心跳数据
function _heatData(){
    var setReq={
        device: phone.deviceId,
        domain: phone.domain,
        type:"18"
    }
    //console.log("发送心跳包:"+ JSON.stringify(setReq));
    if(socket.readyState == WebSocket.OPEN) {
           send(setReq);
    }
}

// 发送数据给服务端
function send(Req) {
    if(!window.WebSocket) {
        return;
    }
    if(socket.readyState == WebSocket.OPEN) {
        // 发送消息
        var message = JSON.stringify(Req);
        socket.send(message);
    } else {
        ztoDialog("连接尚未开启！");
    }
}

// 初始化按钮事件
function initBtnHandler() {
    $('#logout_btn').click(function () {
        if (confirm("确认退出登录！")) {
            _setAgentLoginOut($("#domainS").text().trim(),phone.deviceId,phone.agtId, "0", "Logout", "101", workMode);
        }
    });
    $('#readybtn').click(function () {
        _setAgentStateS($("#domainS").text().trim(),phone.deviceId.trim(),phone.agtId, 0, "Ready", "101", workMode);
    });
   
    $('#makecall_btn').click(function () {
        _makeCall();
    });
    $('#hangup_btn').click(function () {
		_hangupCall();
    });
    $('#answer_btn').click(function () {
        _answerCall();
    });

	$('#senddtmf_btn').click(function () {
        _sendDTMF();
    });

    $('#reconnect_btn').click(function(){
		_reconnectCall();
	});
	
    $('#retrieve_btn').click(function () {
       _retrieveCall();
    });

    $('#hold_btn').click(function () {
        _holdCall();
    });

    $('#ssc_btn').click(function () {
        ssc();
    });

    $('#consult_btn').click(function () {
        consult();
    });

    $('#conference_btn').click(function () {
        _conferenceCall();
    });

    $('#transfer_btn').click(function () {
        _transferCall();
    });

    $('#alternate_btn').click(function () {
        _alternateCall();
    });

	$('#sst_btn').click(function() {
		sst();
	});

	$('#refreshBtn').click(function() {
		_getSkillMetric();
	});

    $('#test2_btn').click(function () {
        _getAgentMetric();
    });

    $('#cls_btn').click(function () {
        document.getElementById('log').innerHTML = "";
    });

    $('#t-op').click(function () {
        if(op_type == 1){
           _consultCall($('#op-num').val());
        }else  if(op_type == 2){
            _sstCall($('#op-num').val());
        }else  if(op_type == 3){
            _sscCall($('#op-num').val());
        }
    });

    $("#callnum").bind("keydown",function(e){
        var theEvent = e || window.event;  // 兼容FF和IE和Opera
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            $("#makecall_btn").click(); //回车执行查询
        }
    });
}

function resetReadyBtn(){
	var ready = '<li id="readybtn" class="invisable"><a itemdata="0" href="#" style="color:#47a447;font-weight:bold;">就绪</a></li>';
    $("#auxreasons").html(ready);
	$('#readybtn').click(function () {
        _setAgentStateS($("#domainS").text().trim(),$("#stationnum").text().trim(),$("#agentnum").text().trim(), 0, "Ready", "101", "ManualIn");
    });
}

// 弹出框
function MessageBox(html){
    $("#alert-content").html(html);
    $("#alertModel").modal('show');
}


function stateChange(nowState) {
    lastStateId = nowState;
    //登出状态
    if (nowState == 0) {
    } else if (nowState == 1) {
        //登陆状态
        $("#zhuce").hide();
        $("#logout").show();
        $("#zhuanjie,#shimang,#guanduan,#shixian,#baochi").removeClass("gray");
        $("#hujiao").removeClass("gray");
        $("#sanfang").removeClass("gray");
        if(phone.rights.isMonitor) $("#banzhang").removeClass("gray");
        if(phone.rights.remoteCti) $("#zhijian").removeClass("gray");
        phone.workTime = $.date.dateFormat(new Date(),"HH:mm:ss");
        /*$('#makecall_btn').addClass("invisable");
        $('#login_btn').removeClass("invisable");
        $('#logout_btn').addClass("invisable");
        $('#hangup_btn').addClass("invisable");
        $('#answer_btn').addClass("invisable");
        $('#hold_btn').addClass("invisable");
        $('#retrieve_btn').addClass("invisable");
        $('#ssc_btn').addClass("invisable");
        $('#consult_btn').addClass("invisable");
        $('#conference_btn').addClass("invisable");
        $('#transfer_btn').addClass("invisable");
        $('#alternate_btn').addClass("invisable");
        $('#sst_btn').addClass("invisable");
        $('#satisfaction_btn').addClass('invisable');
        $('#reconnect_btn').addClass("invisable");*/
    } else if (nowState == 2) {
        //主动呼叫
    } else if (nowState == 3) {
        $(".baochi").show();
        $('.jietong').hide();
        $(".s-tips li").removeClass("curr");
        $(".jietong").addClass("curr");
        //通话状态
    } else if (nowState == 4) {
        $(".baochi").hide();
        $('.jietong').show();
        $(".s-tips li").removeClass("curr");
        $(".baochi").addClass("curr");
        //保持状态
    } else if(nowState == 5) {
        //振铃状态
    } else if (nowState == 6) {
        //第二通话状态
	}else if(nowState == 7){
		//会议的状态
	}else if (nowState == 8) {
        //主动呼叫
    } 
}

// 时间格式化
function time_format() {
    if (s > 0 && (s % 60) == 0) {
        m += 1;
        s = 0;
    }
    if (m > 0 && (m % 60) == 0) {
        h += 1;
        m = 0;
    }
    t = h + ":" + m + ":" + s;
    $('#incalltime').html(t);
    s += 1;
}

function startClock() {
    se = setInterval("time_format()", 1000);
}

function stopClock() {
    clearInterval(se);
    m = h = s = 0;
}

function onMessage(msg) {
    writeLog(msg);
}

function onErrMessage(msg) {
    console.error(msg);
}

function consult() {
    op_type = 1;
    $("#transferModel").modal({
        backdrop: 'static'
    });
}

function sst() {
    op_type = 2;
    $("#transferModel").modal({
        backdrop: 'static'
    });
}

function ssc() {
    op_type = 3;
    $("#transferModel").modal({
        backdrop: 'static'
    });
}